package bsts.util.validation;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LengthValidation20 extends InputVerifier implements ActionListener{

	@Override
	public boolean verify(JComponent input) {
		int fixedTextLength = 20;
		int testTextLength = 0;
		
		JTextField myTextField = (JTextField) input;
        
		testTextLength = myTextField.getText().length();
        
		if (testTextLength <= fixedTextLength){
			return true;
		}else{ 
			return false;
		}

	}
		
	public boolean shouldYieldFocus(JComponent input) {
        boolean inputOK = verify(input);
        String strError = "";

        if (inputOK) {
            return true;
        }


        //Pop up the message dialog.
        strError += "\nPlease enter up to 20 chars only.";
        JOptionPane.showMessageDialog(null, //no owner frame
                                      strError, //text to display
                                      "Invalid Length", //title
                                      JOptionPane.WARNING_MESSAGE);

        //Reinstall the input verifier.
        input.setInputVerifier(this);

        //Beep and then tell whoever called us that we don't
        //want to giveup focus.
        Toolkit.getDefaultToolkit().beep();
        return false;
    }

	@Override
	public void actionPerformed(ActionEvent e) {
		JTextField source = (JTextField)e.getSource();
		shouldYieldFocus(source); //ignore return value
        source.selectAll();	
	}
	
}
